package com.jd.platform.gobrs.client.starter;

import com.jd.platform.gobrs.client.config.BootstrapProperties;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;

/**
 * Dynamic thread pool print banner.
 *
 * @author chen.ma
 * @date 2021/6/20 16:34
 */
@Slf4j
@RequiredArgsConstructor
public class GobrsBannerHandler implements InitializingBean {

    @NonNull
    private final BootstrapProperties properties;

    private final String DYNAMIC_THREAD_POOL = " :: Dynamic ThreadPool :: ";

    private final String HIPPO4J_GITHUB = "GitHub:  https://gitee.com/Memorydoc/gobrs.git";

    private final String HIPPO4J_SITE = "Site:    https://docs.sizegang.cn";

    private final int STRAP_LINE_SIZE = 50;

    @Override
    public void afterPropertiesSet() {
        printBanner();
    }

    private void printBanner() {
        String banner = "   __ _           _                      \n" +
                "  / _` |   ___   | |__      _ _    ___   \n" +
                "  \\__, |  / _ \\  | '_ \\    | '_|  (_-<   \n" +
                "  |___/   \\___/  |_.__/   _|_|_   /__/_  \n";

        if (properties.getBanner()) {
            String version = getVersion();
            version = (version != null) ? " (v" + version + ")" : "no version.";

            StringBuilder padding = new StringBuilder();
            while (padding.length() < STRAP_LINE_SIZE - (version.length() + DYNAMIC_THREAD_POOL.length())) {
                padding.append(" ");
            }
            System.out.println(AnsiOutput.toString(banner, AnsiColor.GREEN, DYNAMIC_THREAD_POOL, AnsiColor.DEFAULT,
                    padding.toString(), AnsiStyle.FAINT, version, "\n\n", HIPPO4J_GITHUB, "\n", HIPPO4J_SITE, "\n"));
        }
    }

    public static String getVersion() {
        final Package pkg = GobrsBannerHandler.class.getPackage();
        return pkg != null ? pkg.getImplementationVersion() : "";
    }

}
